package com.gitee.wsl.mathematics.coordinate.ext

import com.gitee.wsl.mathematics.coordinate.d3.Coordinate3
import com.gitee.wsl.mathematics.geometry.d3.ext.tangentFraction

// distance from this point to a line A-B
fun <T:Number,V:Coordinate3<T, V>> V.distanceToLine(a: V, b: V): T {
    val a0 = (a - this)
    val b0 = (b - this)
    return a0.tangentDistance(b0)
}

// distance from origin to line A-B
fun <T:Number,V:Coordinate3<T, V>> V.tangentDistance(b: Coordinate3<T, *>): T =
    tangentFraction(this,b).distanceAtSegment(this, b)

// when this == 0.0 -> result is a.norm
// when this == 1.0 -> result is b.norm
internal fun <T:Number> T.distanceAtSegment(a: Coordinate3<T, *>, b: Coordinate3<T, *>): T { // norm(a + this * (b - a))
    a.run {
        val f = this@distanceAtSegment
        return norm(a.x + f * (b.x - a.x), a.y + f * (b.y - a.y), a.z + f * (b.z - a.z))
    }
}